<template>
  <div class="app-container">
    <div class="block">
      &nbsp;&nbsp;&nbsp;
      <span class="demonstration">账号</span>
      &nbsp;
      <el-input v-model="username" placeholder="账号/手机号/姓名/邮箱" style="width: 180px" />
      &nbsp;&nbsp;&nbsp;
      <span class="demonstration">注册时间</span>
      &nbsp;
      <el-date-picker
        v-model="value2"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        value-format="yyyy-MM-dd"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
      />
      &nbsp;&nbsp;&nbsp;
      <el-button v-if="btnPermission.getInfoList" type="primary" style="width: 100px" round @click="search">查询</el-button>
      <el-button v-if="btnPermission.getInfoList" type="primary" style="width: 120px" round @click="searchNot">查询注销用户</el-button>
      <el-button v-if="btnPermission.userAdd" type="primary" style="width: 100px" round @click="userAdd">添加用户</el-button>
    </div>
    <br>
    <el-table v-loading="loading" :data="tableData" style="width: 95%;" height="700px" @selection-change="handleSelectionChange">
      <el-table-column v-if="false" align="center" label="ID" />
      <el-table-column align="center" label="账号" prop="username" />
      <el-table-column align="center" label="昵称" prop="name" />
      <el-table-column align="center" label="性别" prop="sex" :formatter="sex" />
      <el-table-column align="center" label="地址" prop="address" :show-overflow-tooltip="true"/>
      <el-table-column align="center" label="邮箱" prop="email" width="220px" />
      <el-table-column align="center" label="手机" prop="phone" />
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch
            v-if="isDelete"
            v-model="scope.row.status"
            :active-value="true"
            :inactive-value="false"
            active-color="#5B7BFA"
            inactive-color="#dadde5"
            @change="updateUserStatus(scope.$index, scope.row)"
          />
          <span v-if="recovery">已注销</span>
        </template>
      </el-table-column>
      <el-table-column width="160px" align="center" label="注册时间" prop="createTime" />
      <el-table-column align="center" label="创建者" prop="createUser" />
      <el-table-column label="操作" width="220px">
        <template slot-scope="scope">
          <el-button v-if="isDelete && btnPermission.resetUserPassword" size="mini" type="primary" @click="changePassword(scope.$index, scope.row)">密码重置</el-button>
          <el-button v-if="isDelete && btnPermission.updateUser" size="mini" @click="updateUser(scope.$index, scope.row)">编辑</el-button>
          <br v-if="isDelete">
          <el-button v-if="isDelete && btnPermission.updateUserRole" size="mini" type="warning" style="margin-top: 10px" @click="userRole(scope.$index, scope.row)">分配角色</el-button>
          <el-button v-if="isDelete && btnPermission.deleteUser" size="mini" type="danger" style="margin-top: 10px" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
          <el-button v-if="recovery && btnPermission.recoveryUser" size="mini" type="danger" style="margin-top: 10px" @click="recoverybtn(scope.$index, scope.row)">恢复</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="width: 90%;"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100, 500]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog title="密码重置" :visible.sync="centerDialogVisible" width="25%" center>
      <el-input v-model="new_pwd.new_password1" placeholder="请输入新密码" show-password />
      <br><br><br>
      <el-input v-model="new_pwd.new_password2" placeholder="请再次输入新密码" show-password />
      <br>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changPasswordClose">取 消</el-button>
        <el-button type="primary" @click="changPasswordConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog v-loading="loading" title="用户修改" :visible.sync="userDialogVisible" width="35%" center :close-on-click-modal="false">
      <el-form :label-position="labelPosition" label-width="80px" :model="userInfo">
        <el-form-item v-if="false" label="id">
          <el-input v-model="userInfo.id" />
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="userInfo.username" disabled />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="userInfo.name" placeholder="输入用户昵称" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio v-model="userInfo.sex" label="1">男</el-radio>
          <el-radio v-model="userInfo.sex" label="0">女</el-radio>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userInfo.email" placeholder="输入邮箱地址" />
        </el-form-item>
        <el-form-item label="手机">
          <el-input
            v-model="userInfo.phone"
            type="text"
            maxlength="11"
            show-word-limit
            placeholder="输入手机号码"
          />
        </el-form-item>
        <el-form-item label="地址">
          <v-distpicker :province="userInfo.city.province" :city="userInfo.city.city" :area="userInfo.city.area" @province="onChangeProvince" @city="onChangeCity" @area="onChangeArea" />
        </el-form-item>
        <el-form-item label="签名">
          <el-input
            v-model="userInfo.remarks"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 6}"
            show-word-limit
            maxlength="500"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changUserClose">取 消</el-button>
        <el-button type="primary" @click="changUserConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog v-loading.fullscreen.lock="fullscreenLoading" title="用户添加" :visible.sync="userAddDialogVisible" width="35%" center>
      <el-form :label-position="labelPosition" label-width="80px" :model="userInfo">
        <el-form-item label="账号">
          <el-input v-model="userInfo.username" placeholder="输入用户账号" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="userInfo.password" placeholder="输入用户密码" show-password />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="userInfo.name" placeholder="输入用户昵称" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio v-model="userInfo.sex" label="1">男</el-radio>
          <el-radio v-model="userInfo.sex" label="0">女</el-radio>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userInfo.email" placeholder="输入邮箱地址" />
        </el-form-item>
        <el-form-item label="手机">
          <el-input
            v-model="userInfo.phone"
            type="text"
            maxlength="11"
            show-word-limit
            placeholder="输入手机号码"
          />
        </el-form-item>
        <el-form-item label="地址">
          <v-distpicker :province="userInfo.city.province" :city="userInfo.city.city" :area="userInfo.city.area" @province="onChangeProvince" @city="onChangeCity" @area="onChangeArea" />
        </el-form-item>
        <el-form-item label="签名">
          <el-input
            v-model="userInfo.remarks"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 6}"
            placeholder="请输入内容"
            show-word-limit
            maxlength="500"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changUserAddClose">取 消</el-button>
        <el-button type="primary" @click="changUserAddConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="分配角色" :visible.sync="userRoleDialogVisible" width="20%" center>
      <template v-for="role in cities">
        <el-checkbox :key="role.id" v-model="checkedCities" border size="medium" :label="role.id" style="width: 150px">{{ role.roleName }}</el-checkbox>
        {{ role.remarks }}
        <br> <br>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="changUseRolerClose">取 消</el-button>
        <el-button type="primary" @click="changUserRoleConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getInfoList, resetUserPassword, updateUserStatus, deleteUser, recoveryUser, getUser, updateUser, getUserRole, updateUserRole, userAdd } from '@/api/user'
import { Message } from 'element-ui'
import VDistpicker from 'v-distpicker'
export default {
  name: 'User',
  components: { VDistpicker },
  data() {
    return {
      total: 0,
      currentPage: 1,
      pageSize: 10,
      multipleSelection: [],
      tableData: [],
      loading: true,
      userDialogVisible: false,
      userAddDialogVisible: false,
      centerDialogVisible: false,
      userRoleDialogVisible: false,
      fullscreenLoading: false,
      recovery: false,
      isDelete: true,
      checkedCities: [],
      cities: [],
      roleUserId: '',
      roleUserName: '',
      labelPosition: 'right',
      new_pwd: {
        new_password1: '',
        new_password2: '',
        new_user_pwd_id: ''
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近六个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 180)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一年',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      value1: '',
      value2: '',
      username: '',
      time: [],
      isNot: 1,
      userInfo: {
        id: '',
        username: '',
        password: '',
        name: '',
        sex: '1',
        city: {
          province: '北京市',
          city: '北京城区',
          area: '东城区'
        },
        address: '',
        email: '',
        phone: '',
        remarks: ''
      },
      btnPermission: {
        getInfoList: false,
        updateUserStatus: false,
        recoveryUser: false,
        updateUser: false,
        updateUserRole: false,
        userAdd: false,
        resetUserPassword: false,
        deleteUser: false
      }
    }
  },
  created() {
    this.getInfoList()
  },
  methods: {
    async getInfoList() {
      const time = this.time == null ? [] : this.time
      const { data } = await getInfoList({
        page: this.currentPage,
        pageSize: this.pageSize,
        time: time,
        username: this.username,
        isNot: this.isNot
      })
      this.total = data.data[0].total
      this.tableData = data.data[0].records
      // 按钮权限设置
      const press = data.data[1]
      for (let s = 0; s < press.length; s++) {
        if (!this.btnPermission[press[s]]) {
          this.btnPermission[press[s]] = true
        }
      }
      this.loading = false
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange: function(pageSize) {
      // 每页条数切换
      this.pageSize = pageSize
      this.handleCurrentChange(this.currentPage)
    },
    handleCurrentChange: function(currentPage) {
      this.loading = true
      // 页码切换
      this.currentPage = currentPage
      this.getInfoList()
    },
    sex(row) {
      if (row.sex) {
        return '女'
      } else {
        return '男'
      }
    },
    search() {
      this.isNot = 1
      this.loading = true
      this.recovery = false
      this.isDelete = true
      this.time = (this.value2 === '' ? [] : this.value2)
      this.getInfoList()
    },
    searchNot() {
      this.isNot = 2
      this.loading = true
      this.recovery = true
      this.isDelete = false
      this.time = (this.value2 === '' ? [] : this.value2)
      this.getInfoList()
    },
    changePassword(index, row) {
      this.centerDialogVisible = true
      this.new_pwd.new_user_pwd_id = row.id
    },
    changPasswordClose() {
      this.new_pwd.new_password1 = ''
      this.new_pwd.new_password2 = ''
      this.new_pwd.new_user_pwd_id = ''
      this.centerDialogVisible = false
    },
    changUserClose() {
      this.userDialogVisible = false
    },
    changUserAddClose() {
      this.userAddDialogVisible = false
    },
    changUserConfirm() {
      const data = this.userInfo.city.province + '-' + this.userInfo.city.city + '-' + this.userInfo.city.area
      this.userInfo.address = data
      this.userInfo.sex = this.userInfo.sex !== '1'
      this.loading = true
      updateUser(this.userInfo).then(res => {
        Message.success(res.data.msg)
        this.getInfoList()
        this.userDialogVisible = false
        this.loading = false
      }).catch(() => {
        this.userInfo.sex = this.userInfo.sex ? '0' : '1'
        this.loading = false
      })
    },
    changUserAddConfirm() {
      if (this.userInfo.username === '' || this.userInfo.username.length < 5) {
        Message.error('请输入账号或账号位数小于5')
      } else if (this.userInfo.password === '' || this.userInfo.password.length < 5) {
        Message.error('请输入密码或密码位数小于5')
      } else {
        const data = this.userInfo.city.province + '-' + this.userInfo.city.city + '-' + this.userInfo.city.area
        this.userInfo.address = data
        this.userInfo.sex = this.userInfo.sex !== '1'
        userAdd(this.userInfo).then(res => {
          Message.success(res.data.msg)
          this.userAddDialogVisible = false
          this.getInfoList()
        }).catch(() => {
          this.userInfo.sex = this.userInfo.sex ? '0' : '1'
        })
      }
    },
    changUseRolerClose() {
      this.userRoleDialogVisible = false
    },
    changUserRoleConfirm() {
      updateUserRole({ id: this.roleUserId, roleId: this.checkedCities, roleUserName: this.roleUserName }).then(res => {
        this.userRoleDialogVisible = false
        Message.success(res.data.msg)
      })
    },
    onChangeProvince(a) {
      this.userInfo.city.province = a.value
    },
    onChangeCity(a) {
      this.userInfo.city.city = a.value
    },
    onChangeArea(a) {
      this.userInfo.city.area = a.value
    },
    changPasswordConfirm() {
      if (this.new_pwd.new_password1 === '') {
        Message.error('请输入密码')
      } else if (this.new_pwd.new_password2 === '') {
        Message.error('请输入确认密码')
      } else if (this.new_pwd.new_password1.length < 5 || this.new_pwd.new_password2.length < 5) {
        Message.error('密码最少6位')
      } else if (this.new_pwd.new_password1 !== this.new_pwd.new_password2) {
        Message.error('两次密码输入不一致')
      } else {
        resetUserPassword(this.new_pwd).then(res => {
          this.new_pwd.new_password1 = ''
          this.new_pwd.new_password2 = ''
          this.new_pwd.new_user_pwd_id = ''
          Message.success(res.data.msg)
          this.centerDialogVisible = false
        }).catch(() => {
          this.loading = false
        })
      }
    },
    updateUserStatus(index, row) {
      this.loading = true
      updateUserStatus({ id: row.id, status: row.status }).then(res => {
        Message.success(res.data.msg)
        this.loading = false
      }).catch(() => {
        row.status = !row.status
        this.loading = false
      })
    },
    deleteUser(index, row) {
      this.loading = true
      this.$confirm('此操作将删除此用户 是否继续?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser({ id: row.id }).then(res => {
          Message.success(res.data.msg)
          this.getInfoList()
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
        this.loading = false
      })
    },
    recoverybtn(index, row) {
      this.loading = true
      this.$confirm('是否恢复此账号，是否继续 ?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        recoveryUser({ id: row.id }).then(res => {
          Message.success(res.data.msg)
          this.getInfoList()
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
        this.loading = false
      })
    },
    updateUser(index, row) {
      this.userDialogVisible = true
      this.userInfo.city = []
      getUser({ id: row.id }).then(res => {
        const { data } = res.data
        this.userInfo.id = data.id
        this.userInfo.username = data.username
        this.userInfo.name = data.name
        this.userInfo.sex = data.sex ? '0' : '1'
        this.userInfo.email = data.email
        this.userInfo.phone = data.phone
        this.userInfo.remarks = data.remarks
        const city = data.address.split('-')
        this.userInfo.city.province = city[0]
        this.userInfo.city.city = city[1]
        this.userInfo.city.area = city[2]
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    userRole(index, row) {
      this.roleUserId = ''
      getUserRole({ id: row.id }).then(res => {
        this.checkedCities = res.data.data[0]
        this.cities = res.data.data[1]
        this.roleUserId = row.id
        this.roleUserName = row.username
      })
      this.userRoleDialogVisible = true
    },
    userAdd() {
      Object.assign(this.$data.userInfo, this.$options.data().userInfo)
      this.userAddDialogVisible = true
    }
  }
}
</script>

